package com.jakewharton.rxbinding4.component;

import static com.jakewharton.rxbinding4.internal.Preconditions.checkMainThread;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.functions.Predicate;
import io.reactivex.rxjava3.openharmony.MainThreadDisposable;
import ohos.agp.components.Text;

final class TextEditorActionEventObservable extends Observable<TextEditorActionEvent> {
    final Text view;
    final Predicate<? super TextEditorActionEvent> handled;

    TextEditorActionEventObservable(@NonNull Text view, Predicate<? super TextEditorActionEvent> handled) {
        this.view = view;
        this.handled = handled;
    }

    @Override
    protected void subscribeActual(@NonNull Observer<? super TextEditorActionEvent> observer) {
        if (!checkMainThread(observer)) {
            return;
        }
        Listener listener = new Listener(view, observer, handled);
        observer.onSubscribe(listener);
        view.setEditorActionListener(listener);
    }

    static final class Listener extends MainThreadDisposable implements Text.EditorActionListener {
        private final Text view;
        private final Observer<? super TextEditorActionEvent> observer;
        private final Predicate<? super TextEditorActionEvent> handled;

        Listener(
                Text view,
                Observer<? super TextEditorActionEvent> observer,
                Predicate<? super TextEditorActionEvent> handled) {
            this.view = view;
            this.observer = observer;
            this.handled = handled;
        }

        @Override
        public boolean onTextEditorAction(int action) {
            TextEditorActionEvent event = TextEditorActionEvent.create(action);
            try {
                if (!isDisposed() && handled.test(event)) {
                    observer.onNext(event);
                    return true;
                }
            } catch (Throwable e) {
                observer.onError(e);
                dispose();
            }
            return false;
        }

        @Override
        protected void onDispose() {
            view.setEditorActionListener(null);
        }
    }
}
